#ifndef __EVENTLOOP_HPP__
#define __EVENTLOOP_HPP__

#include "Accpetor.hpp"
#include "TcpConnect.hpp"

#include <mutex>
#include <functional>
#include <memory>
#include <vector>
#include <map>
using std::vector;
using std::function;
using std::shared_ptr;
using std::map;

namespace wd{

using TcpConnectionptr = shared_ptr<TcpConnection>;
using Callback = function<void(TcpConnectionptr)>;
using Functor = function<void()>;


class EventLoop{

public:
    EventLoop(Acceptor & acceptor);
    ~EventLoop();
    
    void loop();
    void unloop();
    void setAllCallbacks(const Callback & onConnection,
                         const Callback & onMessage,
                         const Callback & onClose);
    void runInLoop(Functor &&); //

private:
    int epollCreate();
    void waitEpollFd();

    void handleNewConnection();
    void handleMessage(int);

    void addEpollReadEvent(int netfd);
    void delEpollReadEvent(int netfd);

    int eventfdCreate();
    void handleReadEvent(); //read
    void wakeup();  //write
    void doPendingFunctors(); //执行callback函数
    

private:
    int _epfd;
    int _eventfd; //用来处理send的信号
    std::mutex _mutex;

    Acceptor & _acceptor;
    bool _isLooping;
    vector<struct epoll_event> _events;
    map<int, TcpConnectionptr> _conns;
    vector<Functor> _pendingFunctors;
    
    Callback _onConnection;
    Callback _onMessage;
    Callback _onClose;

};


}

#endif // __EVENTLOOP_HPP__

